package com.lzp.systemopt

import android.app.ActivityManager
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import com.base.BaseActivity
import com.lzp.systemopt.databinding.ActivityDymIconBinding

/**
 * @description:
 * @author: lxp
 * @date: 2022/11/14 下午3:09
 */
class DymIconActivity : BaseActivity() {

    private val defaultName = "com.lzp.appexp.main.MainActivityNew"
    private val changeName = "com.lzp.appexp.ChangeOne"

    private val binding by lazy { ActivityDymIconBinding.inflate(layoutInflater) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
    }

    override fun initView() {
        super.initView()
        binding.actionBarView.setTitleText("动态切换应用图标名称")
    }

    override fun setListener() {
        super.setListener()
        binding.changeIcon.setOnClickListener {
            binding.root.postDelayed({ changeIcon(defaultName, changeName) }, 3000)
        }

        binding.resetIcon.setOnClickListener {
            binding.root.postDelayed({ changeIcon(changeName, defaultName) }, 3000)
        }
    }

    private fun changeIcon(disName: String, enName: String) {
        val pm = packageManager
        pm.setComponentEnabledSetting(
            ComponentName(this, disName),
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP
        )
        pm.setComponentEnabledSetting(
            ComponentName(this, enName),
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP
        )
        restart(pm)
    }

    public fun restart(pm: PackageManager) {
        val am = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_HOME)
        intent.addCategory(Intent.CATEGORY_DEFAULT)
        val queryIntentActivities = pm.queryIntentActivities(intent, 0)
        queryIntentActivities.forEach {
            am.killBackgroundProcesses(it.activityInfo.packageName)
        }
    }
}